package zqm.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zqm.common.Result;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    // 绝对路径
    private String uploadDir = "E:/JAVA2023/SpringCloud的美食论坛/icooking/icooking_cloud/college_serve/files/";

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, filename);
            file.transferTo(dest);
            // 返回完整图片链接
            String url = "http://localhost:9090/file/" + filename;
            return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "文件上传失败：" + e.getMessage());
        }
    }
} 